package com.shop.loan.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.loan.mapper.LoanOrderSignLogByMybatisMapper;
import com.shop.loan.model.common.Code;
import com.shop.loan.model.common.ResResult;
import com.shop.loan.model.entity.LoanOrderSignLogByMybatis;
import com.shop.loan.rentaldata.RentalDataUtil;
import org.springframework.stereotype.Service;
import xyz.erupt.annotation.fun.OperationHandler;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SeeContractHandler  implements OperationHandler<Object, Void> {

    @Resource
    LoanOrderSignLogByMybatisMapper loanOrderSignLogByMybatisMapper;

    @Resource
    RentalDataUtil rentalDataUtil;

    @Override
    public String exec(List<Object> data, Void unused, String[] param) {
        Object item = data.get(0);
        JSONObject dataJs = JSON.parseObject(JSON.toJSONString(item));
        Long orderId = dataJs.getLongValue("id");

        LoanOrderSignLogByMybatis loanOrderSignLogByMybatis = loanOrderSignLogByMybatisMapper.selectLastByOrderId(orderId);
        if(loanOrderSignLogByMybatis != null && loanOrderSignLogByMybatis.getContractNo() != null){
           ResResult contractRes = rentalDataUtil.getContractInfo(loanOrderSignLogByMybatis.getContractNo());
            if(contractRes.getCode() != Code.SUCCESS.getCode().intValue()){
                return "msg.error('合同获取失败!')";
            }
            JSONObject js = JSON.parseObject(contractRes.getData().toString());
            if(js.containsKey("previewUrl")){
                return "window.open('" + js.getString("previewUrl") + "', '_blank')";
            }
        }
        return "msg.error('合同获取失败!')";
    }
}
